# This script is used to generate the app
import os

from script.exec_sys_cmd import execute_sys_cmd


def create_urls(project_path, app_name):
    urls_path = os.path.join(project_path, app_name, "urls.py")
    template_urls = os.path.join(project_path, "template", "urls", "template_urls.html")
    with open(urls_path, "w+") as fw:
        with open(template_urls, "r+") as fr:
            fw.write(fr.read().replace("{app}", app_name))


def update_base_urls(project_path, app_name):
    base_urls_path = os.path.join(project_path, "backend_django", "urls.py")
    template_base_urls = os.path.join(project_path, "template", "urls", "template_base_urls.html")
    with open(base_urls_path, "r+") as fw:
        fw_content = fw.read()
        with open(template_base_urls, "r+") as fr:
            fr_content = fr.read().replace("{app}", app_name)
            print(fr_content)
            f_content = fw_content.replace("]", fr_content)
            print(f_content)
            with open(base_urls_path, "w") as f:
                f.write(f_content)


def update_models(project_path, app_name):
    models_test_path = os.path.join(project_path, app_name, "models_test.py")
    models_app_path = os.path.join(project_path, app_name, f"models_{app_name}.py")
    to_dict = {
    }
    with open(models_app_path, "r+") as fw:
        fw_content_list = fw.readlines()
        with open(models_test_path, 'a+') as f:
            for i in fw_content_list:
                if "from django.db import models" in i or i.startswith("#"):
                    continue
                if "Field" in i:
                    field = i.split("=")
                    field_name = field[0].strip()
                    if "DateTimeField" in field[1]:
                        to_dict[field_name] = f"self.{field_name}.strftime('%Y-%m-%d %H:%M:%S')"
                    else:
                        to_dict[field_name] = f"self.{field_name}"
                f.write(i)
            content = "    def to_dict(self):\n"
            content += "        return {\n"
            content += "            'id': self.id,\n"
            for k, v in to_dict.items():
                content += f"            '{k}': {v},\n"
            content += "        }\n"
            f.write(content)


def generate_views(project_path, app_name: str):
    base_views_path = os.path.join(project_path, "template", f"{app_name}_views.py")
    template_base_views = os.path.join(project_path, "template", "views", "template_views.html")
    with open(base_views_path, "w+") as fw:
        with open(template_base_views, "r+") as fr:
            fr_content = fr.read().replace("{app}", app_name).replace("{model_table}", app_name.capitalize())
            fw.write(fr_content)


def is_exist_file(file_path):
    if os.path.exists(file_path):
        pass
    else:
        f = open(file_path, "w")
        f.close()


if __name__ == '__main__':
    print("start".center(50, "="))
    app_name = "user"
    project_path = os.path.dirname(os.path.dirname(__file__))
    print(project_path)
    # generate_django_app = f"python manage.py startapp {app_name}"
    # ls = "chdir"
    # ret_code, res = execute_sys_cmd(ls)
    # print(f"return_code={ret_code}, res={res}")
    # create_urls(project_path, app_name)
    # update_base_urls(project_path, app_name)
    # update_models(project_path, app_name)
    generate_views(project_path, app_name)
